//
//  ImageDownLoader.m
//  UI 17 Day
//
//  Created by lanou3g on 15/7/1.
//  Copyright (c) 2015年 任志程. All rights reserved.
//

#import "ImageDownLoader.h"

@implementation ImageDownLoader


#pragma mark - block传值的网络请求 -
- (void) requestImageUrl:(NSString *)imageUrl
            successBlock:(imageDownLoadSuccess)successBlock
              errorBlock:(imageDownLoadError)errorBlock {
    
    self.successBlock = successBlock;
    self.errorBlock = errorBlock;
    
//下载之前先检查本地是否已经有图片
    UIImage *image = [self loadLocalImage:imageUrl];
//将图片转换成NSData
    NSData *imageData = UIImagePNGRepresentation(image);
    
//如果从本地加载到了图片，就直接跳出，不用下载
    if (imageData) {
        self.successBlock(imageData);
        return;
    }
    
//创建URL
    NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            self.successBlock(data);
            
//将下载完成的图片存储到本地,缓存
            [data writeToFile:[self imageFilePath:imageUrl] atomically:YES];
            
        }
        if (connectionError) {
            self.errorBlock(connectionError);
        }
    }];
}





#pragma mark - 代理传值的网络请求 -
//创建Url对象
- (void)requestImageUrl:(NSString *)imageUrl andDelegate:(id<ImageDownFinishDelegate>)delegate {

//在方法中直接设置代理
    self.delegate = delegate;
    
//下载之前先检查本地是否已经有图片
    UIImage *image = [self loadLocalImage:imageUrl];
//将图片转换成NSData
    NSData *imageData = UIImagePNGRepresentation(image);
    
//如果从本地加载到了图片，就直接跳出，不用下载
    if (imageData) {
        [_delegate imageDownLoadSuccess:imageData];
        return;
    }
    
    
//1.创建URL对象,防止地址中出现中文字符，在创建URL的时候首先进行utf-8转码
    NSURL *url = [NSURL URLWithString:[imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//2.创建request对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
//3.发送异步请求,因为图片信息较大防止UI出现卡顿现象
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
//请求成功，调用协议中声明的成功方法
        if (data) {
            [_delegate imageDownLoadSuccess:data];
            
//下载成功，将图片保存到本地
            [data writeToFile:[self imageFilePath:imageUrl] atomically:YES];
            
        }
        
//请求失败，调用协议中声明的失败方法
        if (connectionError) {
            [_delegate imageDownLoadError:connectionError];
        }
    }];


}




#pragma  mark - 加载本地图片 -

- (UIImage *)loadLocalImage:(NSString *)imageUrl {
//获取图像的路径
    NSString *filtPath = [self imageFilePath:imageUrl];
    UIImage *image = [UIImage imageWithContentsOfFile:filtPath];
//判断是否获取到了图片
    if (image != nil) {
        return image;
    }
//没有获取到就去下载图片
    return nil;
}






#pragma mark - 获取图片的路径 -
- (NSString *)imageFilePath:(NSString *)imageUrl {
//获取caches的文件路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
//创建DownLoadImage文件夹
    NSString *downloadIamgePath = [cachesPath stringByAppendingPathComponent:@"DownloadImages"];
//创建管理文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
//判断文件夹是否存在
    if (![fileManager fileExistsAtPath:downloadIamgePath]) {
//如果不存在就创建
        [fileManager createDirectoryAtPath:downloadIamgePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
//拼接出图片文件在沙盒中的路径，因为URL有"/"，要在存入文件之前替换掉，用"_"代替
    NSString *imageName = [imageUrl stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    NSString *imageFilePath = [downloadIamgePath stringByAppendingPathComponent:imageName];
    
    
    return imageFilePath;
    
}

























@end
